<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="bk1wz1wzS4">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css">


  <meta name="keywords" content="实用,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0">






<meta name="description" content="Array.prototype.slice.call(arguments)应用Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组1234var a=&amp;#123;length:2,0:&apos;first&apos;,1:&apos;second&apos;&amp;#125;;Array.prototype.slice.call(a);//  [&quot;first&quot;,&quot;second&quot;]">
<meta name="keywords" content="实用">
<meta property="og:type" content="article">
<meta property="og:title" content="javascript知识点">
<meta property="og:url" content="https://youandme66.github.io/2017/04/27/first/index.html">
<meta property="og:site_name" content="腊月的季节">
<meta property="og:description" content="Array.prototype.slice.call(arguments)应用Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组1234var a=&amp;#123;length:2,0:&apos;first&apos;,1:&apos;second&apos;&amp;#125;;Array.prototype.slice.call(a);//  [&quot;first&quot;,&quot;second&quot;]">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-04-27T14:45:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="javascript知识点">
<meta name="twitter:description" content="Array.prototype.slice.call(arguments)应用Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组1234var a=&amp;#123;length:2,0:&apos;first&apos;,1:&apos;second&apos;&amp;#125;;Array.prototype.slice.call(a);//  [&quot;first&quot;,&quot;second&quot;]">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'youandme'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://youandme66.github.io/2017/04/27/first/">





  <title> javascript知识点 | 腊月的季节 </title>
  <script>
  (function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">腊月的季节</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope="" itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://youandme66.github.io/2017/04/27/first/">

  <span style="display:none" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <meta itemprop="name" content="腊月的季节">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="腊月的季节">
    <span style="display:none" itemprop="logo" itemscope="" itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="腊月的季节" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                javascript知识点
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-04-27T00:00:00+08:00">
                2017-04-27
              </time>
            

            

            
          </span>

          
            <span class="post-category">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
            <!--noindex-->
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                  <a href="/2017/04/27/first/#comments" itemprop="discussionUrl">
                    <span class="post-comments-count hc-comment-count" data-xid="2017/04/27/first/" itemprop="commentsCount"></span>
                  </a>
                </span>
              </span>
              <!--/noindex-->
            
          

          

          
          
             <span id="/2017/04/27/first/" class="leancloud_visitors" data-flag-title="javascript知识点">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="Array-prototype-slice-call-arguments-应用"><a href="#Array-prototype-slice-call-arguments-应用" class="headerlink" title="Array.prototype.slice.call(arguments)应用"></a>Array.prototype.slice.call(arguments)应用</h3><p>Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a=&#123;<span class="attr">length</span>:<span class="number">2</span>,<span class="number">0</span>:<span class="string">'first'</span>,<span class="number">1</span>:<span class="string">'second'</span>&#125;;</span><br><span class="line"><span class="built_in">Array</span>.prototype.slice.call(a);<span class="comment">//  ["first","second"] </span></span><br><span class="line"><span class="keyword">var</span> a=&#123;<span class="attr">length</span>:<span class="number">2</span>&#125;;</span><br><span class="line"><span class="built_in">Array</span>.prototype.slice.call(a);<span class="comment">//  [undefined, undefined]</span></span><br></pre></td></tr></table></figure></p>
<p>可能刚开始学习js的童鞋并不是很能理解这句为什么能实现这样的功能。比如我就是一个，所以，来探究一下。</p>
<p>首先，slice有两个用法，一个是String.slice,一个是Array.slice，第一个返回的是字符串，第二个返回的是数组，这里我们看第2个。<br>Array.prototype.slice.call(arguments)能够将arguments转成数组，那么就是arguments.toArray().slice();到这里，是不是就可以说Array.prototype.slice.call(arguments)的过程就是先将传入进来的第一个参数转为数组，再调用slice？<br>再看call的用法，如下例子<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="keyword">this</span>);    <span class="comment">// 'littledu'</span></span><br><span class="line">     <span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="keyword">this</span>);      <span class="comment">//  Object</span></span><br><span class="line">     <span class="built_in">console</span>.log(<span class="keyword">this</span> <span class="keyword">instanceof</span> <span class="built_in">String</span>);    <span class="comment">// true</span></span><br><span class="line">&#125;</span><br><span class="line">a.call(<span class="string">'littledu'</span>);</span><br></pre></td></tr></table></figure></p>
<p>可以看出，call了后，就把当前函数推入所传参数的作用域中去了，不知道这样说对不对，但反正this就指向了所传进去的对象就肯定的了。<br>到这里，基本就差不多了，我们可以大胆猜一下slice的内部实现，如下<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.prototype.slice = <span class="function"><span class="keyword">function</span>(<span class="params">start,end</span>)</span>&#123;</span><br><span class="line">     <span class="keyword">var</span> result = <span class="keyword">new</span> <span class="built_in">Array</span>();</span><br><span class="line">     start = start || <span class="number">0</span>;</span><br><span class="line">     end = end || <span class="keyword">this</span>.length; <span class="comment">//this指向调用的对象，当用了call后，能够改变this的指向，也就是指向传进来的对象，这是关键</span></span><br><span class="line">     <span class="keyword">for</span>(<span class="keyword">var</span> i = start; i &lt; end; i++)&#123;</span><br><span class="line">          result.push(<span class="keyword">this</span>[i]);</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>大概就是这样吧，理解就行，不深究。<br>最后，附个转成数组的通用函数<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> toArray = <span class="function"><span class="keyword">function</span>(<span class="params">s</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Array</span>.prototype.slice.call(s);</span><br><span class="line">    &#125; <span class="keyword">catch</span>(e)&#123;</span><br><span class="line">            <span class="keyword">var</span> arr = [];</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>,len = s.length; i &lt; len; i++)&#123;</span><br><span class="line">                <span class="comment">//arr.push(s[i]);</span></span><br><span class="line">                   arr[i] = s[i];  <span class="comment">//据说这样比push快</span></span><br><span class="line">            &#125;</span><br><span class="line">             <span class="keyword">return</span> arr;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="javascript的call和apply函数"><a href="#javascript的call和apply函数" class="headerlink" title="javascript的call和apply函数"></a>javascript的call和apply函数</h3><p>每个JavaScript函数都会有很多附属的（attached）方法，包括toString()、call()以及apply()。听起来，你是否会感到奇怪，一个函数可能会有属于它自己的方法，但是记住，JavaScript中的每个函数都是一个对象。看一下 这篇文章 ，复习一下（refresher）JavaScript特性。你可能还想知道JavaScript中函数和方法的区别。我认为“函数”和“方法”的描述，仅仅是JavaScript的习惯约定而已。函数立足于它们自己（例如：alert()），而方法是函数内部一个对象的属性（dictionary）,我们通过对象来调用方法。每个JavaScript对象都有一个toString()方法，下面通过代码举例说明，在一个函数对象中，我们可以使用toString()方法。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"> alert(<span class="string">'x'</span>);</span><br><span class="line">&#125;</span><br><span class="line">alert(foo.toString());</span><br></pre></td></tr></table></figure></p>
<p>因为函数都是对象，它们有自己的属性和方法。我们可以把它们看作数据（data）。这篇文章，我们只关注两个函数的方法apply()以及call()。<br>我们从下面的代码开始<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">10</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"> alert(<span class="keyword">this</span>.x);</span><br><span class="line">&#125;</span><br><span class="line">f();</span><br></pre></td></tr></table></figure></p>
<p>我们定义了一个全局函数f()。f()通过this关键字访问变量x，但是需要注意的是，我们不能通过一个对象的实例来调用这个函数。this指向的是什么对象呢？this会指向这个全局对象。我们的变量x就是在这个全局对象中定义的。上面的代码能够正常运行，运行结果会显示一个对话框，对话框中显示10。<br>我们可以通过this来调用call()和apply()。正如下面的例子展示如何使用call()：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">var</span> o = &#123; <span class="attr">x</span> : <span class="number">15</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"> alert(<span class="keyword">this</span>.x);</span><br><span class="line">&#125;</span><br><span class="line">f();</span><br><span class="line">f.call(o);</span><br></pre></td></tr></table></figure></p>
<p>首先调用f()将会显示10的对话框，因为this这个时候指向的是全局对象。然后我们调用f函数的call()方法，传入的参数是o，运行结果显示的是o中x属性的值15。call()方法会用它的第一个参数作为f函数的this指针。也就是说，我们会告诉运行时，f函数中的this指向的是哪个对象。<br>this跳转听起来有些滑稽，甚至对于C++、Java以及C#程序员来说有些反常。这些都是ECMAScript中有趣的部分。<br>通过call()也可以给函数传递参数：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">var</span> o = &#123; <span class="attr">x</span> : <span class="number">15</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"> alert(<span class="keyword">this</span>.x);</span><br><span class="line">&#125;</span><br><span class="line">f();</span><br><span class="line">f.call(o);</span><br></pre></td></tr></table></figure></p>
<p>apply()和call()类似的，只是apply()要求第二个参数必须是一个数组。这个数组会作为参数传递给目标函数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">x</span> : <span class="number">15</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">message</span>) </span>&#123;</span><br><span class="line"> alert(message);</span><br><span class="line"> alert(<span class="keyword">this</span>.x);</span><br><span class="line">&#125;</span><br><span class="line">f(<span class="string">'invoking f'</span>);</span><br><span class="line">f.apply(o, [<span class="string">'invoking f through apply'</span>]);</span><br></pre></td></tr></table></figure></p>
<p>apply()方法是很有用的，因为我们可以创建一个函数而不用去关心目标方法的参数。这个函数可以通过apply()的第二个数组参数来传递额外的参数给方法。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">x</span> : <span class="number">15</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params">message1</span>) </span>&#123;</span><br><span class="line"> alert(message1 + <span class="keyword">this</span>.x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f2</span>(<span class="params">message1, message2</span>) </span>&#123;</span><br><span class="line"> alert(message1 + (<span class="keyword">this</span>.x * <span class="keyword">this</span>.x) + message2);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">g</span>(<span class="params">object, func, args</span>) </span>&#123;</span><br><span class="line"> func.apply(object, args);</span><br><span class="line">&#125;</span><br><span class="line">g(o, f1, [<span class="string">'the value of x = '</span>]);</span><br><span class="line">g(o, f2, [<span class="string">'the value of x squared = '</span>, <span class="string">'. Wow!'</span>]);</span><br></pre></td></tr></table></figure></p>
<p>这样的语法有点问题。为了调用apply()方法，我们强制目标函数使用数组中的参数。幸运的是，有一个方法可以让这种语法更简单。在此之前，我们必须先介绍一个：参数标识符。<br>在JavaScript中，其实每个函数都有一个可变长度的参数列表。这意味着，即使一个函数只有一个参数的时候，我们也可以传递5个参数给它。下面的代码不会有错误，而且结果显示的是“H”。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">message</span>) </span>&#123;</span><br><span class="line"> alert(message);</span><br><span class="line">&#125;</span><br><span class="line">f(<span class="string">'H'</span>, <span class="string">'e'</span>, <span class="string">'l'</span>, <span class="string">'l'</span>, <span class="string">'o'</span>);</span><br></pre></td></tr></table></figure></p>
<p>在f()中，如果我们不想去接受其他的参数，我们可以用关键字arguments。arguments代表一个参数对象，它有一个代表长度的属性类似于数组。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">message</span>) </span>&#123;</span><br><span class="line"> <span class="comment">// message的值和arguments[0]是一样的</span></span><br><span class="line"> <span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="built_in">arguments</span>.length; i++)&#123;</span><br><span class="line">  message += <span class="built_in">arguments</span>[i];</span><br><span class="line"> &#125;</span><br><span class="line"> alert(message);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 结果显示“Hello”</span></span><br><span class="line">f(<span class="string">'H'</span>, <span class="string">'e'</span>, <span class="string">'l'</span>, <span class="string">'l'</span>, <span class="string">'o'</span>);</span><br></pre></td></tr></table></figure></p>
<p>你应该知道，严格来讲，arguments不是一个数组。arguments有一个length属性，但是没有split、push、pop方法。在前面的g()函数中，我们可以从arguments中拷贝需要的参数，组成数组，然后把这个数组传递给apply()。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">x</span> : <span class="number">15</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">message1, message2</span>) </span>&#123;</span><br><span class="line"> alert(message1 + ( <span class="keyword">this</span>.x * <span class="keyword">this</span>.x) + message2);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">g</span>(<span class="params">object, func</span>) </span>&#123;</span><br><span class="line"> <span class="comment">// arguments[0] = object</span></span><br><span class="line"> <span class="comment">// arguments[1] = func</span></span><br><span class="line"> <span class="keyword">var</span> args = [];</span><br><span class="line"> <span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">2</span>; i &lt; <span class="built_in">arguments</span>.length; i++) &#123;</span><br><span class="line">  args.push(<span class="built_in">arguments</span>[i]);</span><br><span class="line"> &#125;</span><br><span class="line"> func.apply(object, args);</span><br><span class="line">&#125;</span><br><span class="line">g(o, f, <span class="string">'The value of x squared = '</span>, <span class="string">'. Wow!'</span>);</span><br></pre></td></tr></table></figure></p>
<h3 id="javascript逻辑运算符”-”和”-amp-amp-”"><a href="#javascript逻辑运算符”-”和”-amp-amp-”" class="headerlink" title="javascript逻辑运算符”||”和”\&amp;\&amp;”"></a>javascript逻辑运算符”||”和”\&amp;\&amp;”</h3><p>一、先来说说||（逻辑或）,从字面上来说，只有前后都是false的时候才返回false，否则返回true。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="literal">true</span>||<span class="literal">false</span>);    <span class="comment">// true</span></span><br><span class="line">alert(<span class="literal">false</span>||<span class="literal">true</span>);    <span class="comment">// true</span></span><br><span class="line">alert(<span class="literal">true</span>||<span class="literal">true</span>);        <span class="comment">// true</span></span><br><span class="line">alert(<span class="literal">false</span>||<span class="literal">false</span>);    <span class="comment">// false</span></span><br></pre></td></tr></table></figure></p>
<p>但是，从深层意义上来说的话，却有另一番天地，试下面代码<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(0||1);</span><br></pre></td></tr></table></figure></p>
<p>显然，我们知道，前面0意味着false,而后面1意味着true,那么上面的结果应该是true,而事实返回的结果是1。再看下面代码：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(2||1);</span><br></pre></td></tr></table></figure></p>
<p>我们知道，前面2是true,后面1也是true,那返回结果又是什么呢？测试结果是2,继续看：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'a'</span>||1);</span><br></pre></td></tr></table></figure></p>
<p>同样，前面’a’是true，后面1也是true;测试结果是’a’,下面<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">''</span>||1);</span><br></pre></td></tr></table></figure></p>
<p>由上，我们知道前面’’是false,后面1是true,而返回结果是1。再看下面<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'a'</span>||0);</span><br></pre></td></tr></table></figure></p>
<p>前面’a’是true，而后面0是false,返回结果是’a’，继续下面<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'a'</span>||<span class="string">'b'</span>);</span><br></pre></td></tr></table></figure></p>
<p>前面’a’是true,后面’b’是false,返回结果是’a’，我们继续下面<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">''</span>||0);</span><br></pre></td></tr></table></figure></p>
<p>前面’’是false,后面0同样是false,返回结果是0<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(0||<span class="string">''</span>);</span><br></pre></td></tr></table></figure></p>
<p>前面0是false，后面’’是false，返回结果是’’<br>这就意味</p>
<p>1、只要“||”前面为false,不管“||”后面是true还是false，都返回“||”后面的值。</p>
<p>2、只要“||”前面为true,不管“||”后面是true还是false，都返回“||”前面的值。<br>二、下面说说&amp;&amp;（逻辑与）,从字面上来说，只有前后都是true的时候才返回true，否则返回false。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="literal">true</span>&amp;&amp;<span class="literal">false</span>);    // <span class="literal">false</span></span><br><span class="line">alert(<span class="literal">true</span>&amp;&amp;<span class="literal">true</span>);    // <span class="literal">true</span></span><br><span class="line">alert(<span class="literal">false</span>&amp;&amp;<span class="literal">false</span>);    // <span class="literal">false</span></span><br><span class="line">alert(<span class="literal">false</span>&amp;&amp;<span class="literal">true</span>);    // <span class="literal">false</span></span><br></pre></td></tr></table></figure></p>
<p>然后，根据上面经验，我们看看“&amp;&amp;”号前后，不单单是布尔类型的情况。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">''</span>&amp;&amp;1);</span><br></pre></td></tr></table></figure></p>
<p>结是返回’’,“&amp;&amp;”前面’’是false,后面是1是true。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">''</span>&amp;&amp;0);</span><br></pre></td></tr></table></figure></p>
<p>结是返回’’,“&amp;&amp;”前面’’是false,后面是0也是false。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'a'</span>&amp;&amp;1);</span><br></pre></td></tr></table></figure></p>
<p>结是返回1,“&amp;&amp;”前面’’a是true,后面是1也是true。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'a'</span>&amp;&amp;0);</span><br></pre></td></tr></table></figure></p>
<p>结是返回0,“&amp;&amp;”前面’’a是true,后面是0是false。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'a'</span>&amp;&amp;<span class="string">''</span>);</span><br></pre></td></tr></table></figure></p>
<p>结是返回’’,“&amp;&amp;”前面’’a是true,后面是’’是false。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(0&amp;&amp;<span class="string">'a'</span>);</span><br></pre></td></tr></table></figure></p>
<p>结是返回0,“&amp;&amp;”前面’’0是false,后面是’a’是true。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(0&amp;&amp;<span class="string">''</span>);</span><br></pre></td></tr></table></figure></p>
<p>结是返回0,“&amp;&amp;”前面’’0是false,后面是’’也是false。<br>这意味着</p>
<p>1、只要“&amp;&amp;”前面是false，无论“&amp;&amp;”后面是true还是false，结果都将返“&amp;&amp;”前面的值;<br>2、只要“&amp;&amp;”前面是true，无论“&amp;&amp;”后面是true还是false，结果都将返“&amp;&amp;”后面的值;<br>让我们总结一下：<br>1、只要“||”前面为false，无论“||”后面是true还是false，结果都返回“||”后面的值。<br>2、只要“||”前面为true，无论“||”后面是true还是false，结果都返回“||”前面的值。<br>3、只要“&amp;&amp;”前面是false，无论“&amp;&amp;”后面是true还是false，结果都将返“&amp;&amp;”前面的值;<br>4、只要“&amp;&amp;”前面是true，无论“&amp;&amp;”后面是true还是false，结果都将返“&amp;&amp;”后面的值;<br>由上两个测试可知，逻辑运算符，“||”和“&amp;&amp;”都是遵行短路原则，只要确定符号前面的真假，既可确定返回值。<br>需要说明的是“&amp;&amp;”的优先级是高于“||”的，下面测试：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(1||<span class="string">'a'</span>&amp;&amp;2);</span><br></pre></td></tr></table></figure></p>
<p>返回结果是1。<br>根据反证原理，我们假设“||”的优先级不低于“&amp;&amp;”（这里只所以用“不低于”，是为了同时证明等级相同的情况）。<br>根据上面我们得出的结论（1），（1||’a’）将返回前面的值1，(1&amp;&amp;2)根据结论(4)应该返回后面的值2。这显然不对，由此可知“&amp;&amp;”的优先级是高于“||”的。</p>
<h3 id="javascript-splice-方法"><a href="#javascript-splice-方法" class="headerlink" title="javascript splice()方法"></a>javascript splice()方法</h3><p>splice() 方法向/从数组中添加/删除项目，然后返回被删除的项目。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;script type=<span class="string">"text/javascript"</span>&gt;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> arr = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">6</span>)</span><br><span class="line">arr[<span class="number">0</span>] = <span class="string">"George"</span></span><br><span class="line">arr[<span class="number">1</span>] = <span class="string">"John"</span></span><br><span class="line">arr[<span class="number">2</span>] = <span class="string">"Thomas"</span></span><br><span class="line">arr[<span class="number">3</span>] = <span class="string">"James"</span></span><br><span class="line">arr[<span class="number">4</span>] = <span class="string">"Adrew"</span></span><br><span class="line">arr[<span class="number">5</span>] = <span class="string">"Martin"</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">document</span>.write(arr + <span class="string">"&lt;br /&gt;"</span>)</span><br><span class="line">arr.splice(<span class="number">2</span>,<span class="number">0</span>,<span class="string">"William"</span>)</span><br><span class="line"><span class="built_in">document</span>.write(arr + <span class="string">"&lt;br /&gt;"</span>)</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>输出:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">George,John,Thomas,James,Adrew,Martin</span><br><span class="line">George,John,William,Thomas,James,Adrew,Martin</span><br></pre></td></tr></table></figure></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/实用/" rel="tag"># 实用</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/04/26/third/" rel="next" title="log4js模块">
                <i class="fa fa-chevron-left"></i> log4js模块
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/04/27/second/" rel="prev" title="javascript事件监听器">
                javascript事件监听器 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="腊月的季节">
          <p class="site-author-name" itemprop="name">腊月的季节</p>
          <p class="site-description motion-element" itemprop="description">腊月的季节的个人博客</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">160</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">72</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              我的其他足迹
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/qq_33433029" title="CSDN博客" target="_blank">CSDN博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://github.com/youandme66" title="GitHub" target="_blank">GitHub</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/users/767025e0c4df/timeline" title="我的简书" target="_blank">我的简书</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities" title="我的知乎" target="_blank">我的知乎</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Array-prototype-slice-call-arguments-应用"><span class="nav-number">1.</span> <span class="nav-text">Array.prototype.slice.call(arguments)应用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#javascript的call和apply函数"><span class="nav-number">2.</span> <span class="nav-text">javascript的call和apply函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#javascript逻辑运算符”-”和”-amp-amp-”"><span class="nav-number">3.</span> <span class="nav-text">javascript逻辑运算符”||”和”\&amp;\&amp;”</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#javascript-splice-方法"><span class="nav-number">4.</span> <span class="nav-text">javascript splice()方法</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">腊月的季节</span>
</div>


<div class="powered-by">
   <a class="theme-link" href="http://www.jianshu.com/users/767025e0c4df/timeline">我的简书</a> 
</div>

<div class="theme-info">
  链接 -
  <a class="theme-link" href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities">
    我的知乎
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>


  



  




	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 93245, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 93245, xid: "2017/04/27/first/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/93245/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("EAvSG3QtXW1dqzq5WQ5CjH7S-gzGzoHsz", "2aiWv7vIfVY4CjKc49aPBHFX");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

</body>
</html>
